from django import forms
from web import models
from web.forms.bootstrap import BootStrapForm
from django.core.exceptions import ValidationError
from web.forms.widgets import ColorRadioSelect 


class ProjectModelForm(BootStrapForm,forms.ModelForm):

    bootstrap_class_exclude = ['color']
    # desc = forms.CharField(widget=forms.Textarea())
    class Meta:
        model = models.Project
        fields = ['name','color','desc']
        widgets = {
            'desc':forms.Textarea,
            'color':ColorRadioSelect(attrs={
                'class':'color-radio' 
            })
            #'color':forms.RadioSelect
        }
    def __init__(self,request,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.request = request

    def clean_name(self):
        """项目校验"""
        # 1.当前用户是否已创建过此项目
        name = self.cleaned_data['name']
        print('name:----------->',name)
        # 数据库中查询所有人是否创建过这个项目，其它人也可能创建了这个项目
        # exists = models.Project.objects.filter(name=name)
        # 查询当前用户是否创建过这个项目名
        exists = models.Project.objects.filter(name=name,creator=self.request.saas.user)
        if exists:
            raise ValidationError('项目名已存在')

        # 2.当前用户是否还有额度进行创建项目
        # 当前用户最多能创建的项目
        max_num = self.request.saas.price_policy.project_num

        # 现在已经创建的项目个数
        count = models.Project.objects.filter(creator=self.request.saas.user).count()
        if count >= max_num:
            raise ValidationError('项目个数超限，请购买相应套餐')

        return name